import QueryMaterial2 from "@/components/QueryMaterial2";
import { s_getTableInfo } from "@/services/basis";
import { ActionType, EditableFormInstance, EditableProTable, ProCard, ProColumns, ProForm, ProFormInstance, ProFormText, ProTable } from "@ant-design/pro-components"
import { Button, Space, Tag,Image, Modal, message, Row, Col } from "antd";
import moment from "moment";
import { useEffect, useRef, useState } from "react";

const App:React.FC=()=>{
  const [openApply,setOpenApply]=useState(false);
  const [openOrder,setOpenOrder]=useState(false);
  const [selectedRecords,setSelectedRecords]=useState([]);
  const [material,setMaterial]=useState([]);

  const [etype,setEtype]=useState(1);
  const formRef_apply=useRef<ProFormInstance>();
  const editable_apply=useRef<EditableFormInstance>();
  const actionRef_apply=useRef<ActionType>();

  //当组件选择物料时，更新表格并重载--
          useEffect(()=>{
             if(material.length>0){
             var x:any[]=editable_apply.current?.getRowsData?.();
             // alert(JSON.stringify(x));
             if(x==undefined)
                x=[];
             material.map((item:any)=>{
                x?.push({rid:Math.random().toFixed(10),id:Math.random().toFixed(10).toString(),
                          material_id:item.id,code:item.code,name:item.name,
                          invstd:item.invstd,invstd2:item.invstd2,munit_name:item.munit_name,  
                          require_date:moment().format('YYYY-MM-DD'),quantity_require:1,  
                          userdefine_id:'[]',pic:item.pic,
                          iscombine:0,
                });
             });
             // alert(JSON.stringify(x));
            //  setDataSource(x);
              
              formRef_apply.current?.setFieldValue('editable_apply',x);
              actionRef_apply.current?.reloadAndRest?.();
          }
          },[material]);

    interface DataType{
// id,x_id,source_type,id source_did,source_mid,operate_time,operater_id,status,material_id,userdefine_id,userdefine_name,
// quantity_require,quantity_done,require_date,org_id,memo,custom_id,
// code,name,invstd,invstd2,pic,munit_name,org_name,operater_name,source_sale_order_vouchcode 
rid?:number,
id?:number,x_id?:number,source_type?:number,source_did?:number,source_mid?:number,
operate_time?:number,operater_id?:number,status?:number,material_id?:number,userdefine_id?:string,
userdefine_name?:string,quantity_require?:number,quantity_done?:number,require_date?:string,
org_id?:number,memo?:string,custom_id?:number,vouch_code?:string,iscombine?:number,
code?:string,name?:string,invstd?:string,invstd2?:string,pic?:string,munit_name?:string,
org_name?:string,operater_name?:string,source_sale_order_vouchcode ?:string
    };

    const columns:ProColumns<DataType>[]=[
      {dataIndex:'pic',title:'图片' ,editable:false,
        render:(text)=>{
            var pic=text=="-"||text==undefined?"":"/basis_api/file/get?filename="+text;
            return <Image src={pic}  
                   style={{width:50,height:50}} alt='无' />
       },
     },
        {dataIndex:'source_type',title:'需求来源',valueType:'radio',
          valueEnum:{1:{text:'需求计划'},2:{text:'请购'},3:{text:'销售单'}}
        },
        {dataIndex:'source_sale_order_vouchcode',title:'来源销售单'},
        {dataIndex:'vouch_code',title:'请购单号'},
     
        {dataIndex:'code',title:'SKU码'},{dataIndex:'name',title:'商品名称'},
        {dataIndex:'invstd',title:'规格',},{dataIndex:'invstd2',title:'型号'},
        {dataIndex:'munit_name',title:'计量单位'},{dataIndex:'quantity_require',title:'需求数量'},
        {dataIndex:'require_date',title:'需求日期',valueType:'date'},
        {dataIndex:'iscombine',title:'是否合并采购',valueType:'radio',
          valueEnum:{0:{text:'否'},1:{text:'是'}}
        },
        {dataIndex:'org_name',title:'制单部门'},{dataIndex:'operater_name',title:'制单人'},
        {dataIndex:'priority',title:'优先级', 
            render:(text:any)=>text.indexOf('急')>=0?<Tag color="red" style={{width:60}}>{text}</Tag>:text,
             
        },
        {dataIndex:'status',title:'状态',
            render:(text)=>text=='关闭'?<Tag color="blue" style={{width:60}}>关闭</Tag>:text,
        },
    ];

 //打开请购单
 function beginApply(type:number){
    if(type==0&&selectedRecords.length==0)
       message.warning('请选择要编辑的行');
    else{
       setEtype(type);
       setOpenApply(true);
    };
 };   

 //退出请购单
  function endApply(){
    setEtype(1);
    setOpenApply(false);
  };

// 保存请购单
async function saveApply(){
    alert(JSON.stringify(formRef_apply.current?.getFieldsValue()));
};


 //==============================================================================================================
    return <>
      <ProCard title='采购需求池'  style={{height:800,overflow:'auto'}}
         extra={<Space>
            <Button onClick={()=>beginApply(1)}>新增请购</Button> 
            <Button onClick={()=>beginApply(0)}>编辑请购</Button> 
            <Button>审核</Button> 
            <Button>弃审</Button> 
            <Button>转采购订单</Button>
            <Button>关闭</Button>
            <Button>删除</Button>
            <Button>恢复</Button>
         </Space>}
      >
        <ProTable<DataType>
          options={false} 
          columns={columns}
          search={false}
          rowKey='rid'
          rowSelection={{
            type:'checkbox',
            onChange(selectedRowKeys, selectedRows:any, info) {
              setSelectedRecords(selectedRows);
            },
          }}
          request={async ()=>{
            const x=await s_getTableInfo({source:'v_purchase_require_pool',x_id:1,id:0});
            return{
              data:x.data,
              success:true,
            }
          }}
        />
      </ProCard>

      {/* 请购单------------------------------------------------------------------ */}
      <Modal open={openApply} destroyOnClose closable onCancel={()=>setOpenApply(false)} onClose={()=>setOpenApply(false)}
          width='90%' okButtonProps={{hidden:true}} cancelButtonProps={{hidden:true}}  style={{top:10}}>
           <ProForm formRef={formRef_apply} submitter={false} layout="horizontal" labelAlign="left" 
              labelCol={{offset:0,span:5}} labelWrap
              onFinish={()=>saveApply()}>
            <ProCard title={etype==0?'新增请购单':'编辑请购单'} style={{height:900,overflow:'auto'}}
               extra={<Space>
                   {/* <Button>引用销售单</Button> */}
                   <QueryMaterial2 setData={setMaterial} type='checkbox' x_id={1}/>
                   <Button>保存</Button>
                   <Button>退出</Button>
               </Space>}
            > 
           <Row gutter={8}>
                <Col span={8}>
                   <ProFormText name='vouch_code' label='请购单号' width={200} />
                   <ProFormText name='org_id' label='请购部门' width={200} />
                </Col>
                <Col span={8}>
                   <ProFormText name='purchasetype_id' label='请购类型' width={200} />
                   <ProFormText name='deliverdate' label='需求日期' width={200} />
                </Col>
                <Col span={8}>
                   <ProFormText name='status' label='状态' width={200} />
                   <ProFormText name='memo' label='备注' width={500} />
                </Col>
                  
              </Row>  
              <EditableProTable<DataType>
                 name='editable_apply'
                 editableFormRef={editable_apply}
                 actionRef={actionRef_apply}
                 columns={columns}
                 rowKey='rid'
                 options={false}
                 search={false}
                 editable={{
                  type:'multiple'
                 }}
                 recordCreatorProps={false}
                 scroll={{y:600}}
                />
                </ProCard>   
            </ProForm>
      </Modal>
    </>;
};

export default App;